import 'package:dio/dio.dart';
import 'package:bot_toast/bot_toast.dart';
import 'extra_keys.dart';
import '../utils/toast_util.dart' show Toast;

class ToastInterceptor extends Interceptor {
  CancelFunc? _loadingFunc;

  @override
  void onError(
    DioError err,
    ErrorInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc?.call();
    // 当需要toast时, 弹出错误提示
    if (err.requestOptions.extra[ExtraKeys.NEED_ERROR_TOAST] != false) {
      Toast.showError(err.response?.data?.msg);
    }
    return handler.next(err);
  }

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc?.call();
    if (options.extra[ExtraKeys.NEED_LOADING] != false) {
      var loadingMsg = options.extra[ExtraKeys.NEED_LOADING_MSG];
      _loadingFunc = Toast.showLoading(loadingMsg: loadingMsg);
    }
    return handler.next(options);
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc?.call();
    // 当需要toast时, 弹出提示
    if (response.requestOptions.extra[ExtraKeys.NEED_TOAST] != false) {
      Toast.showSuccess(response.data?.msg);
    }
    return handler.next(response);
  }
}
